package com.lemon.boot.common.handler;

import com.lemon.boot.common.exception.CustomException;
import com.lemon.boot.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * @author 李猛
 * @datetime 2023/10/7 14:52
 * @description 类对象
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 权限异常，默认状态码是401
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public Result<String> exception(AccessDeniedException e) {
        log.error("权限异常:{}", e.getMessage());
        return Result.fail(HttpStatus.FORBIDDEN.value(), "未授权操作！");
    }

    /**
     * SQL异常，默认状态码是500
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = SQLException.class)
    public Result<String> exception(SQLException e) {
        log.error("SQL异常:{}", e.getMessage());
        return Result.fail("SQL异常！");
    }

    /**
     * 自定义异常，默认状态码是500
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    public Result<String> exception(CustomException e) {
        log.error("自定义异常:{}", e.getMessage());
        return Result.fail(StringUtils.hasText(e.getMessage()) ? e.getMessage() : "系统异常！");
    }

    /**
     * 全局异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    public Result<String> exception(RuntimeException e) {
        log.error("系统异常:{}", e.getMessage());
        e.printStackTrace();
        return Result.fail("系统异常！");
    }
}
